package cn.pzhu.temp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

import cn.pzhu.pojo.User;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1. 处理编码 2‘
        request.setCharacterEncoding("utf-8");
        // 2. 接收参数 4‘
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String path = request.getContextPath();
        //3. 数据验证 4'
        if (username == null || password == null) {
            //9.保存错误信息，重定向到错误页面 2‘
            request.getSession().setAttribute("msg", "前端数据接收异常");
            response.sendRedirect(path + "/error.jsp");
            return;
        }
        if (username.equals("")) {
            request.getSession().setAttribute("msg", "用户名不能为空");
            response.sendRedirect(path + "/error.jsp");
            return;
        }
        if (password.equals("")) {
            request.getSession().setAttribute("msg", "密码不能为空");
            response.sendRedirect(path + "/error.jsp");
            return;
        }
        //4. 数据封装（接收的信息较多）
        User user = new User(username, password, null);
        //5. 初始化模型层，调用方法（业务层处理）
        //6. 根据业务层处理结果，执行不同的操作
        if (!password.equals("123456")) {
            request.getSession().setAttribute("msg", "密码错误");
            response.sendRedirect(path + "/error.jsp");
            return;
        }
        //7. 保存用户信息 2'
        request.getSession().setAttribute("user", user);
        //8. 符合预期，转到正确的页面 2'
        response.sendRedirect(path + "/index.jsp");
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}